package com.woyao;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.squareup.picasso.Picasso;
import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.ChanceSummary;
import com.woyao.core.model.Manager;
import com.woyao.core.service.ChanceService;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;

import static com.woyao.WoyaoooApplication.userId;

public class ChanceSummaryAdapter extends PagerAdapter {
    private List<ChanceSummary> chances;  //

    private Changed onChanged;
    private LayoutInflater mInflater;
    private Context context ;
    ProgressDialog progressDialog;


    public ChanceSummaryAdapter(Context thecontext, ArrayList<ChanceSummary> data) {

        chances = data;
        context = thecontext;
        this.mInflater = LayoutInflater.from(thecontext);
    }

    public interface Changed{
        void view( Integer pos );
    }

    public void setChangedHandler(Changed changed){
        this.onChanged = changed;
    }
    @Override
    public void setPrimaryItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        super.setPrimaryItem(container, position, object);

        onChanged.view( position );
        Log.i("tag",position +"  showing");
    }

    @Override   //返回要滑动的VIew的个数
    public int getCount() {
        return chances.size();
    }

    @Override  //来判断pager的一个view是否和instantiateItem方法返回的object有关联
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        Log.i("tag", "  isViewFromObject");
        return view==object;
    }

    @Override  //从当前container中删除指定位置（position）的View;
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        Log.i("tag", "destroyItem " + position);
        container.removeView((View)object);
    }

    @NonNull
    @Override  //第一：将当前视图添加到container中，第二：返回当前View
    public Object instantiateItem(@NonNull ViewGroup container, final int position) {
        Log.i("tag", "instantiateItem " + position);
        View view = mInflater.inflate(R.layout.chance_summary_layout,container,false);
        TextView theTitle = (TextView) view.findViewById(R.id.id_fulltitle);
        final VideoView video = (VideoView) view.findViewById(R.id.videoView);
        final ImageView image = (ImageView) view.findViewById(R.id.pic);
        TextView desc = (TextView) view.findViewById(R.id.chance_desc);
        de.hdodenhof.circleimageview.CircleImageView owner_avartar  = (de.hdodenhof.circleimageview.CircleImageView) view.findViewById(R.id.owner_avatar);
        TextView owner_displayname = (TextView) view.findViewById(R.id.owner_displayname);
        TextView owner_company_job = (TextView) view.findViewById(R.id.owner_company_job);
        TextView owner_location = (TextView) view.findViewById(R.id.owner_location);
        LinearLayout detailmore = (LinearLayout) view.findViewById(R.id.id_chance_detailmore);
        LinearLayout advice = (LinearLayout) view.findViewById(R.id.id_advice);

        LinearLayout markBtn = (LinearLayout) view.findViewById(R.id.id_mark);
        LinearLayout referBtn = (LinearLayout) view.findViewById(R.id.id_refer);

        final ChanceSummary c =  chances.get(position);

        final ImageView markImageView = (ImageView) view.findViewById(R.id.id_mark_image);

        if  (c.getMarked()){
            markImageView.setImageResource(R.drawable.love_full);
        }else{
            markImageView.setImageResource(R.drawable.love_empty);
        }

        markBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                markIt( position ,  markImageView );
            }
        });

        referBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                referIt(position,image);
            }
        });



        theTitle.setText(c.getTitle() );
        desc.setText(c.getDescription());
        final Manager manager = c.getManager();
        owner_displayname.setText( manager.getDisplayname() );
        owner_company_job.setText(manager.getRole());
        owner_location.setText(manager.getLocation());

        Picasso.with(context)
                .load(manager.getSnailview())
                .into(owner_avartar );


        owner_avartar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.putExtra("id", manager.getId() );
                intent.setClass(context, PersonViewActivity.class);
                context.startActivity(intent);
            }
        });

        advice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loadAdvice( c.getPid(),c.getMid());

            }
        });

        detailmore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.putExtra("from", "main");
                intent.putExtra("pid", c.getPid());
                intent.putExtra("id", c.getId());
                intent.setClass(context, ChanceViewActivity.class);
                context.startActivity(intent);
            }
        });

        if (!c.getVideo().equals("")) {
            video.setVisibility(View.VISIBLE);
            image.setVisibility(View.INVISIBLE);
            video.setVideoPath(c.getVideo());
            video.start();
            c.setImage(  Common.getVideoSnapFile(c.getVideo(), context) );

            video.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (video.isPlaying()) {
                        video.pause();
                    }else{
                        video.start();
                    }
                }
            });

        } else {
                video.setVisibility(View.INVISIBLE);
                image.setVisibility(View.VISIBLE);
        }

        Picasso.with(context)
                .load(c.getImage())
                .into(image );


        container.addView(view);
        return view;
    }

    private void markIt( Integer  pos , final ImageView markImageView ) {
        final ChanceSummary chance = chances.get(pos);
        chance.setMarked(!chance.getMarked());

        AsyncTask<Void, Void, BaseResponse> task =
                new AsyncTask<Void, Void, BaseResponse>() {
                    @Override
                    protected BaseResponse doInBackground(Void... params) {
                        ChanceService svc = ServiceFactory.get(ChanceService.class);

                        Call<BaseResponse> responseCall = svc.mark(userId,chance.getPid(),chance.getId(),chance.getMarked().toString().toLowerCase());
                        try {
                            BaseResponse response = responseCall.execute().body();
                            return  response;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(final BaseResponse response) {

                        if ( response != null) {
                            if (response.isSuccess()) {
                                if  (chance.getMarked()){
                                    markImageView.setImageResource(R.drawable.love_full);
                                }else{
                                    markImageView.setImageResource(R.drawable.love_empty);
                                }
                            }else{
                                Toast.makeText(context,response.getMessage(),Toast.LENGTH_SHORT).show();
                            }

                        }else{
                            Toast.makeText(context,"处理失败",Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    protected void onCancelled() {

                    }
                };
        task.execute((Void) null);

    }



    private  void loadAdvice(final Integer pid,final Integer mid){
        progressDialog = new ProgressDialog(context);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在加载信息······");
        progressDialog.show();
        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                ChanceService svc = ServiceFactory.get(ChanceService.class);
                Call<BaseResponse> responseCall = svc.getAdvice(WoyaoooApplication.userId,mid,pid);
                BaseResponse ret = null ;
                try {
                    ret = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = null;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final BaseResponse response) {
                progressDialog.dismiss();
                if (response != null) {

                    if (response.isSuccess()) {
                        Intent intent = new Intent();
                        intent.putExtra("from", "main");
                        intent.putExtra("id", pid);
                        intent.putExtra("type", "match");
                        intent.setClass(context, TalkActivity.class);
                        context.startActivity(intent);
                    }else{
                        Dialog alertDialog = new AlertDialog.Builder(context).
                                setTitle("信息").
                                setMessage(response.getMessage()).
                                setIcon(R.drawable.ic_launcher).
                                setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        if (response.getCondition().equals("charge")){
                                            renderMoney();
                                        }
                                    }
                                }).
                                setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                }).create();
                        alertDialog.show();


                    }
//                    Common.alert( ChanceActivity.this,response.getMessage());
                } else {
                    Common.alert( context,"系统发生错误");
                }
            }

            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task.execute((Void) null);

    }

    private void renderMoney( ){
        Intent intent = new Intent();
        intent.putExtra("money", 100.0);
        intent.setClass(context, MoneyActivity.class);
        context.startActivity(intent);
    }



    private void referIt( int pos , final ImageView mainImageView){
        ChanceSummary chance = chances.get(pos);
        Intent intent = new Intent();
        intent.setClass(context, ReferActivity.class);
        intent.putExtra("title", chance.getTitle());

        Manager theManager = chance.getManager();


        intent.putExtra("description", chance.getDescription() + "\n " +theManager.getRole() + "\n " + theManager.getLocation() + "\n " +  theManager.getDisplayname() );

        intent.putExtra("id", chance.getId());

        mainImageView.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(mainImageView.getDrawingCache());
        mainImageView.setDrawingCacheEnabled(false);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        int options = 90;
        while (baos.toByteArray().length / 1024 > 32) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset(); // 重置baos即清空baos
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
        }
        intent.putExtra("photo_bmp", baos.toByteArray());

        context.startActivity(intent);
    }

}
